/**
 * FormRelDivLucro.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormRelDivLucro.java
 *
 * Created on 05/07/2009, 21:33:03
 */

package frames;

import java.text.ParseException;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
import plagio.postgres.ConnectionPostgres;
import utils.*;

/**
 *
 * @author jmsandy
 */
public class FormRelDivLucro extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="Fields">
    ConnectionPostgres conn       = new ConnectionPostgres();
    SimpleDateFormat sdf          = new SimpleDateFormat("dd/MM/yyyy");
    Date dtInicial                = null;
    Date dtFinal                  = null;
    Integer situacao              = null;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructor">
    /** Creates new form FormRelDivLucro */
    public FormRelDivLucro() {
        initComponents();
        initializeMyComponentes();
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormRelDivLucro().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        textDtInicial = new javax.swing.JFormattedTextField();
        lbDataInicio = new javax.swing.JLabel();
        lbIntervalo = new javax.swing.JLabel();
        textDtFinal = new javax.swing.JFormattedTextField();
        panelBotao = new javax.swing.JPanel();
        btnCancelar = new javax.swing.JButton();
        btnVisualizar = new javax.swing.JButton();

        setTitle("Filtro - Divisão de Lucros");
        setName("formRelDivLucros"); // NOI18N
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Filtro", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("SansSerif", 0, 12))); // NOI18N

        textDtInicial.setBackground(java.awt.Color.white);
        try {
            textDtInicial.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textDtInicial.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textDtInicial.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textDtInicial.setFont(new java.awt.Font("SansSerif", 0, 12));
        textDtInicial.setPreferredSize(new java.awt.Dimension(54, 26));

        lbDataInicio.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDataInicio.setText("Data de Início");

        lbIntervalo.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbIntervalo.setText("à");

        textDtFinal.setBackground(java.awt.Color.white);
        try {
            textDtFinal.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        textDtFinal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textDtFinal.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);
        textDtFinal.setFont(new java.awt.Font("SansSerif", 0, 12));
        textDtFinal.setPreferredSize(new java.awt.Dimension(54, 26));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbDataInicio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textDtInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(4, 4, 4)
                .addComponent(lbIntervalo)
                .addGap(3, 3, 3)
                .addComponent(textDtFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(17, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {textDtFinal, textDtInicial});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbIntervalo, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(textDtFinal, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textDtInicial, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbDataInicio, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {textDtFinal, textDtInicial});

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnCancelar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        btnVisualizar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnVisualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/print.png"))); // NOI18N
        btnVisualizar.setText("Visualizar");
        btnVisualizar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnVisualizarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(btnVisualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(34, Short.MAX_VALUE))
        );
        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar)
                    .addComponent(btnVisualizar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(11, 11, 11))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-348)/2, (screenSize.height-186)/2, 348, 186);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Events">
    // Cancela visualizacao
    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        this.dispose();
}//GEN-LAST:event_btnCancelarMouseClicked
    // Visualiza Relatorio
    private void btnVisualizarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnVisualizarMouseClicked
        try{
            // Verifica se a busca pode ser realizada
            if(validSearch()){
                // Recupera os fornecedores que satisfacam os filtros
                this.setVisible(false);

                // Cria os parametros para ser passado
                conn = ConnectionSystem.connectionSystem();
                JasperPrint jp = GeradorRelatorio.generateReport(
                 "relDivLucro.jasper", mountParameter(), conn.getConnection());

                JasperViewer.viewReport(jp, false);

            } else{
                JOptionPane.showMessageDialog(this, "Datas incompativeis.");
            }
        } catch(Exception ex){}
}//GEN-LAST:event_btnVisualizarMouseClicked
    //</editor-fold>
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnVisualizar;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lbDataInicio;
    private javax.swing.JLabel lbIntervalo;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JFormattedTextField textDtFinal;
    private javax.swing.JFormattedTextField textDtInicial;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    private void initializeMyComponentes(){
        initializeFields();
    }

    // Inicializa os campos com o valores padroes
    private void initializeFields(){
        textDtFinal.setText(null);
        textDtInicial.setText(null);
    }

    // Valida os campos para busca
    private Boolean validSearch(){
        Boolean valid = true;
        try{
            dtInicial = textDtInicial.getText().equals("  /  /    ") ?
                null : new Date( sdf.parse(textDtInicial.getText()).getTime());

            dtFinal = textDtFinal.getText().equals("  /  /    ") ?
                null : new Date( sdf.parse(textDtFinal.getText()).getTime());

            valid = (dtInicial != null && dtFinal == null) ? false : true;

            if(valid && dtInicial != null && dtFinal != null){
                valid = dtFinal.getTime() >= dtInicial.getTime() ? true : false;
            }
        }
        catch(ParseException ex){
            ex.printStackTrace();
            valid = false;
        }
        return valid;
    }

    // Monta a lista de parametros para busca
    private HashMap mountParameter() {
        HashMap parameter = new HashMap();
        // Pega a conexao para fornecer ao relatorio

        try{
//            parameter.put("REPORT_CONNECTION", conn.getConnection());
            parameter.put("DTINICIAL",
                    dtInicial != null ? textDtInicial.getText() : "01/01/1970");
            parameter.put("DTFINAL",
                        dtFinal != null ? textDtFinal.getText() : "31/12/2100");
        }
        catch(Exception ex){}
        return parameter;
    }
    //</editor-fold>
}
